package com.pingan.haofang.searchcloud.common.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * TODO: 请添加描述
 *
 * @author liujunjun380
 * @date 2018/11/19
 * @since 1.0.0
 */
public class RedisQueue<T> {

    static Logger LOG = LoggerFactory.getLogger(RedisQueue.class);

    private RedisTemplate redisTemplate;
    private String key;
    private BoundListOperations<String, T> listOperations;//noblocking

    private RedisQueueListener listener;//异步回调

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setListener(RedisQueueListener listener) {
        this.listener = listener;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public void bound() throws Exception {
        listOperations = redisTemplate.boundListOps(key);
    }

    /**
     * 从队列的头，插入
     */
    public void pushFromHead(T value) {
        listOperations.leftPush(value);
    }

    public void pushFromTail(T value) {
        listOperations.rightPush(value);
    }

    /**
     * noblocking
     *
     * @return null if no item in queue
     */
    public T removeFromHead() {
        return listOperations.leftPop();
    }

    public T removeFromTail() {
        return listOperations.rightPop();
    }

    public class ListenerThread extends Thread {

        @Override
        public void run() {

            while (true) {
                T value = removeFromHead();//cast exceptionyou should check.
                //逐个执行
                if (value != null) {
                    try {
                        listener.onMessage(value);
                    } catch (Exception e) {
                        LOG.error(e.getMessage(), e);
                    }
                } else {
                    break;
                }
            }

        }
    }
}
